import { useRef } from 'react';

export default function useMemoComparative<T, C = any[]>(
	factory: () => T,
	condition: C,
	comparator: (prev: C, next: C) => boolean,
): T {
	const ref = useRef<{ value: T; condition: C }>();

	if (!ref.current || comparator(ref.current.condition, condition)) {
		ref.current = {
			value: factory(),
			condition,
		};
	}

	return ref.current.value;
}
